package com.rem.flink.flink5Watermark;

import com.rem.flink.flink2Source.ClickSource;
import com.rem.flink.flink2Source.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.HashSet;

/**
 * 处理窗口函数 ProcessWindowFunction 可以获取 Context上下文
 * <p>
 * 获取窗口访问量
 *
 * @author Rem
 * @date 2022-10-11
 */

public class ProcessWindowFunctionTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner((SerializableTimestampAssigner<Event>) (element, recordTimestamp) -> element.getTimestamp()))
                .keyBy(e -> true)
                .window(TumblingEventTimeWindows.of(Time.seconds(3)))

                /**
                 * 处理窗口函数
                 * 使用用于检索额外信息的上下文在键控（分组）窗口上评估的函数的基本抽象类。
                 * 类型形参：
                 * < IN > – 输入值的类型。
                 * < OUT > – 输出值的类型。
                 * < KEY > – 密钥的类型。
                 * < W > – 可以应用此窗口函数的Window类型
                 */
                .process(new ProcessWindowFunction<Event, String, Boolean, TimeWindow>() {
                    @Override
                    public void process(Boolean aBoolean, ProcessWindowFunction<Event, String, Boolean, TimeWindow>.Context context,
                                        Iterable<Event> elements, Collector<String> out) {
                        HashSet<String> hashSet = new HashSet<>();

                        for (Event element : elements) {
                            hashSet.add(element.getUser());
                        }

                        // 结合窗口信息，包装输出内容
                        long start = context.window().getStart();
                        long end = context.window().getEnd();
                        out.collect("窗口: " + new Timestamp(start) + " ~ " + new Timestamp(end)
                                + " 的独立访客数量是：" + hashSet.size());
                    }
                })
                .print();

                env.execute();
    }
}
